/*
 * Copyright (C) 2005-2011 MaNGOS <http://www.getmangos.com/>
 *
 * Copyright (C) 2008-2011 Trinity <http://www.trinitycore.org/>
 *
 * Copyright (C) 2010-2011 ArkCORE <http://www.arkania.net/>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include "gamePCH.h"
#include "Common.h"
#include "DBCEnums.h"
#include "ObjectMgr.h"
#include "World.h"
#include "WorldPacket.h"
#include "DatabaseEnv.h"
#include "AchievementMgr.h"
#include "ArenaTeam.h"
#include "CellImpl.h"
#include "GameEventMgr.h"
#include "GridNotifiersImpl.h"
#include "Guild.h"
#include "Language.h"
#include "Player.h"
#include "SpellMgr.h"
#include "DisableMgr.h"
#include "ScriptMgr.h"
#include "MapManager.h"
#include "Battleground.h"
#include "BattlegroundAB.h"
#include "Map.h"
#include "InstanceScript.h"
#include "zlib.h"

namespace Trinity {
class AchievementChatBuilder {
public:
	AchievementChatBuilder(Player const& pl, ChatMsg msgtype, int32 textId,
			uint32 ach_id) :
			i_player(pl), i_msgtype(msgtype), i_textId(textId), i_achievementId(
					ach_id) {
	}
	void operator()(WorldPacket& data, LocaleConstant loc_idx) {
		char const* text = sObjectMgr->GetArkCoreString(i_textId, loc_idx);

		data << uint8(i_msgtype);
		data << uint32(LANG_UNIVERSAL);
		data << uint64(i_player.GetGUID());
		data << uint32(5);
		data << uint64(i_player.GetGUID());
		data << uint32(strlen(text) + 1);
		data << text;
		data << uint8(0);
		data << uint32(i_achievementId);
	}

private:
	Player const& i_player;
	ChatMsg i_msgtype;
	int32 i_textId;
	uint32 i_achievementId;
};
} // namespace Trinity

bool AchievementCriteriaData::IsValid(
		AchievementCriteriaEntry const* criteria) {
	if (dataType >= MAX_ACHIEVEMENT_CRITERIA_DATA_TYPE) {
		sLog->outErrorDb(
				"Table `achievement_criteria_data` for criteria (Entry: %u) has wrong data type (%u), ignored.",
				criteria->ID, dataType);
		return false;
	}

	switch (criteria->requiredType) {
	case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
	case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
	case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
	case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: // only hardcoded list
	case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
	case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
	case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
	case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
	case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
	case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
	case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
	case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
	case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
	case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
	case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
	case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
	case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
	case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
		break;
	default:
		sLog->outErrorDb(
				"Table `achievement_criteria_data` has data for non-supported criteria type (Entry: %u Type: %u), ignored.",
				criteria->ID, criteria->requiredType);
		return false;
	}

	switch (dataType) {
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE:
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE:
	case ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT:
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE:
		if (!creature.id || !ObjectMgr::GetCreatureTemplate(creature.id)) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE (%u) has non-existing creature id in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType,
					creature.id);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE:
		if (!classRace.class_id && !classRace.race_id) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.",
					criteria->ID, criteria->requiredType, dataType);
			return false;
		}
		if (classRace.class_id
				&& ((1 << (classRace.class_id - 1)) & CLASSMASK_ALL_PLAYABLE)
						== 0) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE (%u) has non-existing class in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType,
					classRace.class_id);
			return false;
		}
		if (classRace.race_id
				&& ((1 << (classRace.race_id - 1)) & RACEMASK_ALL_PLAYABLE) == 0) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE (%u) has non-existing race in value2 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType,
					classRace.race_id);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH:
		if (health.percent < 1 || health.percent > 100) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_LESS_HEALTH (%u) has wrong percent value in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType,
					health.percent);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD:
		if (player_dead.own_team_flag > 1) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD (%u) has wrong boolean value1 (%u).",
					criteria->ID, criteria->requiredType, dataType,
					player_dead.own_team_flag);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA:
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA: {
		SpellEntry const* spellEntry = sSpellStore.LookupEntry(aura.spell_id);
		if (!spellEntry) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell id in value1 (%u), ignored.",
					criteria->ID,
					criteria->requiredType,
					(dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA ?
							"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA" :
							"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType,
					aura.spell_id);
			return false;
		}
		if (aura.effect_idx >= 3) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell effect index in value2 (%u), ignored.",
					criteria->ID,
					criteria->requiredType,
					(dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA ?
							"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA" :
							"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType,
					aura.effect_idx);
			return false;
		}
		if (!spellEntry->EffectApplyAuraName[aura.effect_idx]) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has non-aura spell effect (ID: %u Effect: %u), ignores.",
					criteria->ID,
					criteria->requiredType,
					(dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA ?
							"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA" :
							"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType,
					aura.spell_id, aura.effect_idx);
			return false;
		}
		return true;
	}
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA:
		if (!GetAreaEntryByAreaID(area.id)) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA (%u) has wrong area id in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType, area.id);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL:
		if (level.minlevel > STRONG_MAX_LEVEL) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL (%u) has wrong minlevel in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType,
					level.minlevel);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER:
		if (gender.gender > GENDER_NONE) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER (%u) has wrong gender in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType,
					gender.gender);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT:
		if (!ScriptId) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT (%u) does not have ScriptName set, ignored.",
					criteria->ID, criteria->requiredType, dataType);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY:
		if (difficulty.difficulty >= MAX_DIFFICULTY) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY (%u) has wrong difficulty in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType,
					difficulty.difficulty);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT:
		if (map_players.maxcount <= 0) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT (%u) has wrong max players count in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType,
					map_players.maxcount);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM:
		if (team.team != ALLIANCE && team.team != HORDE) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM (%u) has unknown team in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType, team.team);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK:
		if (drunk.state >= MAX_DRUNKEN) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK (%u) has unknown drunken state in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType,
					drunk.state);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY:
		if (!sHolidaysStore.LookupEntry(holiday.id)) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY (%u) has unknown holiday in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType, holiday.id);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_BG_LOSS_TEAM_SCORE:
		return true; // not check correctness node indexes
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM:
		if (equipped_item.item_quality >= MAX_ITEM_QUALITY) {
			sLog->outErrorDb(
					"Table `achievement_criteria_requirement` (Entry: %u Type: %u) for requirement ACHIEVEMENT_CRITERIA_REQUIRE_S_EQUIPED_ITEM (%u) has unknown quality state in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType,
					equipped_item.item_quality);
			return false;
		}
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_ID:
		if (!sMapStore.LookupEntry(map_id.mapId)) {
			sLog->outErrorDb(
					"Table `achievement_criteria_requirement` (Entry: %u Type: %u) for requirement ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_ID (%u) has unknown map id in value1 (%u), ignored.",
					criteria->ID, criteria->requiredType, dataType,
					map_id.mapId);
			return false;
		}
		return true;
	default:
		sLog->outErrorDb(
				"Table `achievement_criteria_data` (Entry: %u Type: %u) has data for non-supported data type (%u), ignored.",
				criteria->ID, criteria->requiredType, dataType);
		return false;
	}
}

bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source,
		Unit const* target, uint32 miscvalue1 /*= 0*/) const {
	switch (dataType) {
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE:
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE:
		if (!target || target->GetTypeId() != TYPEID_UNIT)
			return false;
		return target->GetEntry() == creature.id;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE:
		if (!target || target->GetTypeId() != TYPEID_PLAYER)
			return false;
		if (classRace.class_id
				&& classRace.class_id != target->ToPlayer()->getClass())
			return false;
		if (classRace.race_id
				&& classRace.race_id != target->ToPlayer()->getRace())
			return false;
		return true;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH:
		if (!target || target->GetTypeId() != TYPEID_PLAYER)
			return false;
		return !target->HealthAbovePct(health.percent);
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD:
		if (target && !target->isAlive())
			if (const Player* player = target->ToPlayer())
				if (player->GetDeathTimer() != 0)
					// flag set == must be same team, not set == different team
					return (player->GetTeam() == source->GetTeam())
							== (player_dead.own_team_flag != 0);
		return false;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA:
		return source->HasAuraEffect(aura.spell_id, aura.effect_idx);
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA: {
		uint32 zone_id, area_id;
		source->GetZoneAndAreaId(zone_id, area_id);
		return area.id == zone_id || area.id == area_id;
	}
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA:
		return target && target->HasAuraEffect(aura.spell_id, aura.effect_idx);
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE:
		return miscvalue1 >= value.minvalue;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL:
		if (!target)
			return false;
		return target->getLevel() >= level.minlevel;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER:
		if (!target)
			return false;
		return target->getGender() == gender.gender;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT:
		return sScriptMgr->OnCriteriaCheck(this, const_cast<Player*>(source),
				const_cast<Unit*>(target));
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY:
		return source->GetMap()->GetSpawnMode() == difficulty.difficulty;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT:
		return source->GetMap()->GetPlayersCountExceptGMs()
				<= map_players.maxcount;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM:
		if (!target || target->GetTypeId() != TYPEID_PLAYER)
			return false;
		return target->ToPlayer()->GetTeam() == team.team;
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK:
		return Player::GetDrunkenstateByValue(source->GetDrunkValue())
				>= DrunkenState(drunk.state);
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY:
		return IsHolidayActive(HolidayIds(holiday.id));
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_BG_LOSS_TEAM_SCORE: {
		Battleground* bg = source->GetBattleground();
		if (!bg)
			return false;
		return bg->IsTeamScoreInRange(
				source->GetTeam() == ALLIANCE ? HORDE : ALLIANCE,
				bg_loss_team_score.min_score, bg_loss_team_score.max_score);
	}
	case ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT: {
		if (!source->IsInWorld())
			return false;
		Map* map = source->GetMap();
		if (!map->IsDungeon()) {
			sLog->outErrorDb(
					"Achievement system call ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT (%u) for achievement criteria %u for non-dungeon/non-raid map %u",
					ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT, criteria_id,
					map->GetId());
			return false;
		}
		InstanceScript* instance = ((InstanceMap*) map)->GetInstanceScript();
		if (!instance) {
			sLog->outErrorDb(
					"Achievement system call ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT (%u) for achievement criteria %u for map %u but map does not have a instance script",
					ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT, criteria_id,
					map->GetId());
			return false;
		}
		return instance->CheckAchievementCriteriaMeet(criteria_id, source,
				target, miscvalue1);
	}
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM: {
		ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(miscvalue1);
		if (!pProto)
			return false;
		return pProto->ItemLevel >= equipped_item.item_level
				&& pProto->Quality >= equipped_item.item_quality;
	}
	case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_ID:
		return source->GetMapId() == map_id.mapId;
	default:
		break;
	}
	return false;
}

bool AchievementCriteriaDataSet::Meets(Player const* source, Unit const* target,
		uint32 miscvalue /*= 0*/) const {
	for (Storage::const_iterator itr = storage.begin(); itr != storage.end();
			++itr)
		if (!itr->Meets(criteria_id, source, target, miscvalue))
			return false;

	return true;
}

AchievementMgr::AchievementMgr(Player *player) {
	m_player = player;
	achievementPoints = 0;
}

AchievementMgr::~AchievementMgr() {
}

void AchievementMgr::Reset() {
	for (CompletedAchievementMap::const_iterator iter =
			m_completedAchievements.begin();
			iter != m_completedAchievements.end(); ++iter) {
		WorldPacket data(SMSG_ACHIEVEMENT_DELETED, 4);
		data << uint32(iter->first);
		m_player->SendDirectMessage(&data);
	}

	for (CriteriaProgressMap::const_iterator iter = m_criteriaProgress.begin();
			iter != m_criteriaProgress.end(); ++iter) {
		WorldPacket data(SMSG_CRITERIA_DELETED, 4);
		data << uint32(iter->first);
		m_player->SendDirectMessage(&data);
	}

	m_completedAchievements.clear();
	achievementPoints = 0;
	m_criteriaProgress.clear();
	DeleteFromDB(m_player->GetGUIDLow());

	// re-fill data
	CheckAllAchievementCriteria();
}

void AchievementMgr::ResetAchievementCriteria(AchievementCriteriaTypes type,
		uint64 miscvalue1, uint64 miscvalue2, bool evenIfCriteriaComplete) {
	sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS,
			"AchievementMgr::ResetAchievementCriteria(%u, %u, %u)", type,
			miscvalue1, miscvalue2);

	if (m_player->GetSession()->GetSecurity()
			> AccountTypes(
					sWorld->getIntConfig(CONFIG_GM_LEVEL_ALLOW_ACHIEVEMENTS)))
		return;

	AchievementCriteriaEntryList const& achievementCriteriaList =
			sAchievementMgr->GetAchievementCriteriaByType(type);
	for (AchievementCriteriaEntryList::const_iterator i =
			achievementCriteriaList.begin(); i != achievementCriteriaList.end();
			++i) {
		AchievementCriteriaEntry const *achievementCriteria = (*i);

		AchievementEntry const *achievement = sAchievementStore.LookupEntry(
				achievementCriteria->referredAchievement);
		if (!achievement)
			continue;

		// don't update already completed criteria if not forced or achievement already complete
		if ((IsCompletedCriteria(achievementCriteria, achievement)
				&& !evenIfCriteriaComplete) || HasAchieved(achievement))
			continue;

		for (uint8 j = 0; j < MAX_CRITERIA_REQUIREMENTS; ++j)
			if (achievementCriteria->additionalRequirements[j].additionalRequirement_type
					== miscvalue1
					&& (!achievementCriteria->additionalRequirements[j].additionalRequirement_value
							|| achievementCriteria->additionalRequirements[j].additionalRequirement_value
									== miscvalue2)) {
				RemoveCriteriaProgress(achievementCriteria);
				break;
			}
	}
}

void AchievementMgr::DeleteFromDB(uint32 lowguid) {
	SQLTransaction trans = CharacterDatabase.BeginTransaction();
	trans->PAppend("DELETE FROM character_achievement WHERE guid = %u",
			lowguid);
	trans->PAppend("DELETE FROM character_achievement_progress WHERE guid = %u",
			lowguid);
	CharacterDatabase.CommitTransaction(trans);
}

void AchievementMgr::SaveToDB(SQLTransaction& trans) {
	if (!m_completedAchievements.empty()) {
		bool need_execute = false;
		std::ostringstream ssdel;
		std::ostringstream ssins;
		for (CompletedAchievementMap::iterator iter =
				m_completedAchievements.begin();
				iter != m_completedAchievements.end(); ++iter) {
			if (!iter->second.changed)
				continue;

			/// first new/changed record prefix
			if (!need_execute) {
				ssdel << "DELETE FROM character_achievement WHERE guid = "
						<< GetPlayer()->GetGUIDLow() << " AND achievement IN (";
				ssins
						<< "INSERT INTO character_achievement (guid, achievement, date) VALUES ";
				need_execute = true;
			}
			/// next new/changed record prefix
			else {
				ssdel << ", ";
				ssins << ", ";
			}

			// new/changed record data
			ssdel << iter->first;
			ssins << "(" << GetPlayer()->GetGUIDLow() << ", " << iter->first
					<< ", " << uint64(iter->second.date) << ")";

			/// mark as saved in db
			iter->second.changed = false;
		}

		if (need_execute)
			ssdel << ")";

		if (need_execute) {
			trans->Append(ssdel.str().c_str());
			trans->Append(ssins.str().c_str());
		}
	}

	if (!m_criteriaProgress.empty()) {
		/// prepare deleting and insert
		bool need_execute_del = false;
		bool need_execute_ins = false;
		std::ostringstream ssdel;
		std::ostringstream ssins;
		for (CriteriaProgressMap::iterator iter = m_criteriaProgress.begin();
				iter != m_criteriaProgress.end(); ++iter) {
			if (!iter->second.changed)
				continue;

			// deleted data (including 0 progress state)
			{
				/// first new/changed record prefix (for any counter value)
				if (!need_execute_del) {
					ssdel
							<< "DELETE FROM character_achievement_progress WHERE guid = "
							<< GetPlayer()->GetGUIDLow()
							<< " AND criteria IN (";
					need_execute_del = true;
				}
				/// next new/changed record prefix
				else
					ssdel << ", ";

				// new/changed record data
				ssdel << iter->first;
			}

			// store data only for real progress
			if (iter->second.counter != 0) {
				/// first new/changed record prefix
				if (!need_execute_ins) {
					ssins
							<< "INSERT INTO character_achievement_progress (guid, criteria, counter, date) VALUES ";
					need_execute_ins = true;
				}
				/// next new/changed record prefix
				else
					ssins << ", ";

				// new/changed record data
				ssins << "(" << GetPlayer()->GetGUIDLow() << ", " << iter->first
						<< ", " << iter->second.counter << ", "
						<< iter->second.date << ")";
			}

			/// mark as updated in db
			iter->second.changed = false;
		}

		if (need_execute_del) // DELETE ... IN (.... _)_
			ssdel << ")";

		if (need_execute_del || need_execute_ins) {
			if (need_execute_del)
				trans->Append(ssdel.str().c_str());
			if (need_execute_ins)
				trans->Append(ssins.str().c_str());
		}
	}
}

void AchievementMgr::LoadFromDB(PreparedQueryResult achievementResult,
		PreparedQueryResult criteriaResult) {
	if (achievementResult) {
		do {
			Field* fields = achievementResult->Fetch();

			uint32 achievementid = fields[0].GetUInt16();

			// don't must happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements()
			AchievementEntry const* achievement = sAchievementStore.LookupEntry(
					achievementid);
			if (!achievement)
				continue;

			CompletedAchievementData& ca =
					m_completedAchievements[achievementid];
			ca.date = time_t(fields[1].GetUInt32());
			ca.changed = false;

			if (AchievementEntry const* pAchievement = sAchievementStore.LookupEntry(achievementid))
				achievementPoints += pAchievement->points;

			// title achievement rewards are retroactive
			if (AchievementReward const* reward = sAchievementMgr->GetAchievementReward(achievement))
				if (uint32 titleId = reward->titleId[GetPlayer()->GetTeam() == ALLIANCE ? 0 : 1])
					if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId))
						if (!GetPlayer()->HasTitle(titleEntry))
							GetPlayer()->SetTitle(titleEntry);
		} while (achievementResult->NextRow());
	}

	if (criteriaResult) {
		do {
			Field* fields = criteriaResult->Fetch();

			uint32 id = fields[0].GetUInt16();
			uint32 counter = fields[1].GetUInt32();
			time_t date = time_t(fields[2].GetUInt32());

			AchievementCriteriaEntry const* criteria =
					sAchievementCriteriaStore.LookupEntry(id);
			if (!criteria) {
				// we will remove not existed criteria for all characters
				sLog->outError(
						"Non-existing achievement criteria %u data removed from table `character_achievement_progress`.",
						id);
				CharacterDatabase.PExecute(
						"DELETE FROM character_achievement_progress WHERE criteria = %u",
						id);
				continue;
			}

			if (criteria->timeLimit
					&& time_t(date + criteria->timeLimit) < time(NULL))
				continue;

			CriteriaProgress& progress = m_criteriaProgress[id];
			progress.counter = counter;
			progress.date = date;
			progress.changed = false;
		} while (criteriaResult->NextRow());
	}
}

void AchievementMgr::SendAchievementEarned(
		AchievementEntry const* achievement) {
	if (GetPlayer()->GetSession()->PlayerLoading())
		return;

	// Don't send for achievements with ACHIEVEMENT_FLAG_HIDDEN
	if (achievement->flags & ACHIEVEMENT_FLAG_HIDDEN)
		return;

#ifdef ARKCORE_DEBUG
	sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr::SendAchievementEarned(%u)", achievement->ID);
#endif

	if (Guild * guild = sObjectMgr->GetGuildById(GetPlayer()->GetGuildId())) {
		Trinity::AchievementChatBuilder say_builder(*GetPlayer(),
				CHAT_MSG_GUILD_ACHIEVEMENT, LANG_ACHIEVEMENT_EARNED,
				achievement->ID);
		Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> say_do(
				say_builder);
		guild->BroadcastWorker(say_do, GetPlayer());

		guild->UpdateMemberData(GetPlayer(),
				GUILD_MEMBER_DATA_ACHIEVEMENT_POINTS, GetAchievementPoints());
	}

	if (achievement->flags
			& (ACHIEVEMENT_FLAG_REALM_FIRST_KILL
					| ACHIEVEMENT_FLAG_REALM_FIRST_REACH)) {
		// broadcast realm first reached
		WorldPacket data(SMSG_SERVER_FIRST_ACHIEVEMENT,
				strlen(GetPlayer()->GetName()) + 1 + 8 + 4 + 4);
		data << GetPlayer()->GetName();
		data << uint64(GetPlayer()->GetGUID());
		data << uint32(achievement->ID);
		data << uint32(0); // 1=link supplied string as player name, 0=display plain string
		sWorld->SendGlobalMessage(&data);
	}
	// if player is in world he can tell his friends about new achievement
	else if (GetPlayer()->IsInWorld()) {
		CellPair p = Trinity::ComputeCellPair(GetPlayer()->GetPositionX(),
				GetPlayer()->GetPositionY());

		Cell cell(p);
		cell.data.Part.reserved = ALL_DISTRICT;
		cell.SetNoCreate();

		Trinity::AchievementChatBuilder say_builder(*GetPlayer(),
				CHAT_MSG_ACHIEVEMENT, LANG_ACHIEVEMENT_EARNED, achievement->ID);
		Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> say_do(
				say_builder);
		Trinity::PlayerDistWorker<
				Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> > say_worker(
				GetPlayer(), sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), say_do);
		TypeContainerVisitor<
				Trinity::PlayerDistWorker<
						Trinity::LocalizedPacketDo<
								Trinity::AchievementChatBuilder> >,
				WorldTypeMapContainer> message(say_worker);
		cell.Visit(p, message, *GetPlayer()->GetMap(), *GetPlayer(),
				sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY));
	}

	WorldPacket data(SMSG_ACHIEVEMENT_EARNED, 8 + 4 + 8);
	data.append(GetPlayer()->GetPackGUID());
	data << uint32(achievement->ID);
	data << uint32(secsToTimeBitFields(time(NULL)));
	data << uint32(0);
	GetPlayer()->SendMessageToSetInRange(&data,
			sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true);
		}

void AchievementMgr::SendCriteriaUpdate(AchievementCriteriaEntry const* entry,
		CriteriaProgress const* progress, uint32 timeElapsed,
		bool timedCompleted) {
	WorldPacket data(SMSG_CRITERIA_UPDATE, 8 + 4 + 8);
	data << uint32(entry->ID);

	// the counter is packed like a packed Guid
	data.appendPackGUID(progress->counter);

	data.append(GetPlayer()->GetPackGUID());
	if (!entry->timeLimit)
		data << uint32(0);
	else
		data << uint32(timedCompleted ? 0 : 1); // this are some flags, 1 is for keeping the counter at 0 in client
	data << uint32(secsToTimeBitFields(progress->date));
	data << uint32(timeElapsed); // time elapsed in seconds
	data << uint32(0); // unk
	GetPlayer()->SendDirectMessage(&data);
}

/**
 * called at player login. The player might have fulfilled some achievements when the achievement system wasn't working yet
 */
void AchievementMgr::CheckAllAchievementCriteria() {
	// suppress sending packets
	for (uint32 i = 0; i < ACHIEVEMENT_CRITERIA_TYPE_TOTAL; ++i)
		UpdateAchievementCriteria(AchievementCriteriaTypes(i));
}

static const uint32 achievIdByArenaSlot[MAX_ARENA_SLOT] = { 1057, 1107, 1108 };
static const uint32 achievIdForDungeon[][4] = {
// ach_cr_id, is_dungeon, is_raid, is_heroic_dungeon
		{ 321, true, true, true }, { 916, false, true, false }, { 917, false,
				true, false }, { 918, true, false, false }, { 2219, false,
				false, true }, { 0, false, false, false } };

/**
 * this function will be called whenever the user might have done a criteria relevant action
 */
void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type,
		uint64 miscvalue1, uint64 miscvalue2, Unit *unit, uint32 time) {
	sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS,
			"AchievementMgr::UpdateAchievementCriteria(%u, %u, %u)", type,
			miscvalue1, miscvalue2);

	if (m_player->GetSession()->GetSecurity()
			> AccountTypes(
					sWorld->getIntConfig(CONFIG_GM_LEVEL_ALLOW_ACHIEVEMENTS)))
		return;

	AchievementCriteriaEntryList const& achievementCriteriaList =
			sAchievementMgr->GetAchievementCriteriaByType(type);
	for (AchievementCriteriaEntryList::const_iterator i =
			achievementCriteriaList.begin(); i != achievementCriteriaList.end();
			++i) {
		AchievementCriteriaEntry const *achievementCriteria = (*i);
		if (sDisableMgr->IsDisabledFor(DISABLE_TYPE_ACHIEVEMENT_CRITERIA,
				achievementCriteria->ID, NULL))
			continue;

		AchievementEntry const *achievement = sAchievementStore.LookupEntry(
				achievementCriteria->referredAchievement);
		if (!achievement)
			continue;

		if ((achievement->factionFlag == ACHIEVEMENT_FACTION_HORDE
				&& GetPlayer()->GetTeam() != HORDE)
				|| (achievement->factionFlag == ACHIEVEMENT_FACTION_ALLIANCE
						&& GetPlayer()->GetTeam() != ALLIANCE))
			continue;

		// don't update already completed criteria
		if (IsCompletedCriteria(achievementCriteria, achievement))
			continue;

		switch (type) {
		// std. case: increment at 1
		case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
		case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
		case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
		case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
		case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS: /* FIXME: for online player only currently */
		case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
		case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
		case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
		case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
		case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
		case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
			// std case: increment at miscvalue1
		case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
		case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
		case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
		case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING:
		case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
		case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
		case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
		case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:/* FIXME: for online player only currently */
		case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED:
		case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED:
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			SetCriteriaProgress(achievementCriteria, miscvalue1,
					PROGRESS_ACCUMULATE);
			break;
			// std case: high value at miscvalue1
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD: /* FIXME: for online player only currently */
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT:
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED:
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED:
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED:
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			SetCriteriaProgress(achievementCriteria, miscvalue1,
					PROGRESS_HIGHEST);
			break;

			// specialized cases

		case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: {
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			if (achievementCriteria->win_bg.bgMapID != GetPlayer()->GetMapId())
				continue;

			// those requirements couldn't be found in the dbc
			AchievementCriteriaDataSet const* data =
					sAchievementMgr->GetCriteriaDataSet(achievementCriteria);
			if (!data || !data->Meets(GetPlayer(), unit))
				continue;

			SetCriteriaProgress(achievementCriteria, miscvalue1,
					PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: {
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			if (achievementCriteria->kill_creature.creatureID != miscvalue1)
				continue;

			// those requirements couldn't be found in the dbc
			AchievementCriteriaDataSet const* data =
					sAchievementMgr->GetCriteriaDataSet(achievementCriteria);
			if (!data || !data->Meets(GetPlayer(), unit))
				continue;

			SetCriteriaProgress(achievementCriteria, miscvalue2,
					PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
			SetCriteriaProgress(achievementCriteria, GetPlayer()->getLevel());
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
			// update at loading or specific skill update
			if (miscvalue1
					&& miscvalue1
							!= achievementCriteria->reach_skill_level.skillID)
				continue;
			if (uint32 skillvalue = GetPlayer()->GetBaseSkillValue(achievementCriteria->reach_skill_level.skillID))
				SetCriteriaProgress(achievementCriteria, skillvalue);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
			// update at loading or specific skill update
			if (miscvalue1
					&& miscvalue1
							!= achievementCriteria->learn_skill_level.skillID)
				continue;
			if (uint32 maxSkillvalue = GetPlayer()->GetPureMaxSkillValue(achievementCriteria->learn_skill_level.skillID))
				SetCriteriaProgress(achievementCriteria, maxSkillvalue);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
			if (m_completedAchievements.find(
					achievementCriteria->complete_achievement.linkedAchievement)
					!= m_completedAchievements.end())
				SetCriteriaProgress(achievementCriteria, 1);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT: {
			SetCriteriaProgress(achievementCriteria,
					GetPlayer()->getRewardedQuests().size());
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY: {
			time_t nextDailyResetTime = sWorld->GetNextDailyQuestsResetTime();
			CriteriaProgress *progress = GetCriteriaProgress(
					achievementCriteria);

			if (!miscvalue1) // Login case.
			{
				// reset if player missed one day.
				if (progress && progress->date < (nextDailyResetTime - 2 * DAY))
					SetCriteriaProgress(achievementCriteria, 0, PROGRESS_SET);
				continue;
			}

			ProgressType progressType;
			if (!progress)
				// 1st time. Start count.
				progressType = PROGRESS_SET;
			else if (progress->date < (nextDailyResetTime - 2 * DAY))
				// last progress is older than 2 days. Player missed 1 day => Retart count.
				progressType = PROGRESS_SET;
			else if (progress->date < (nextDailyResetTime - DAY))
				// last progress is between 1 and 2 days. => 1st time of the day.
				progressType = PROGRESS_ACCUMULATE;
			else
				// last progress is within the day before the reset => Already counted today.
				continue;

			SetCriteriaProgress(achievementCriteria, 1, progressType);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE: {
			// speedup for non-login case
			if (miscvalue1
					&& miscvalue1
							!= achievementCriteria->complete_quests_in_zone.zoneID)
				continue;

			uint32 counter = 0;
			for (RewardedQuestSet::const_iterator itr =
					GetPlayer()->getRewardedQuests().begin();
					itr != GetPlayer()->getRewardedQuests().end(); ++itr) {
				Quest const* quest = sObjectMgr->GetQuestTemplate(*itr);
				if (quest && quest->GetZoneOrSort() >= 0
						&& uint32(quest->GetZoneOrSort())
								== achievementCriteria->complete_quests_in_zone.zoneID)
					counter++;
			}
			SetCriteriaProgress(achievementCriteria, counter);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			if (GetPlayer()->GetMapId()
					!= achievementCriteria->complete_battleground.mapID)
				continue;
			SetCriteriaProgress(achievementCriteria, miscvalue1,
					PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			if (GetPlayer()->GetMapId()
					!= achievementCriteria->death_at_map.mapID)
				continue;
			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_DEATH: {
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			// skip wrong arena achievements, if not achievIdByArenaSlot then normal total death counter
			bool notfit = false;
			for (int j = 0; j < MAX_ARENA_SLOT; ++j) {
				if (achievIdByArenaSlot[j] == achievement->ID) {
					Battleground* bg = GetPlayer()->GetBattleground();
					if (!bg || !bg->isArena()
							|| ArenaTeam::GetSlotByType(bg->GetArenaType()) != j)
						notfit = true;

					break;
				}
			}
			if (notfit)
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON: {
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;

			Map const* map =
					GetPlayer()->IsInWorld() ?
							GetPlayer()->GetMap() :
							sMapMgr->FindMap(GetPlayer()->GetMapId(),
									GetPlayer()->GetInstanceId());
			if (!map || !map->IsDungeon())
				continue;

			// search case
			bool found = false;
			for (int j = 0; achievIdForDungeon[j][0]; ++j) {
				if (achievIdForDungeon[j][0] == achievement->ID) {
					if (map->IsRaid()) {
						// if raid accepted (ignore difficulty)
						if (!achievIdForDungeon[j][2])
							break; // for
					} else if (GetPlayer()->GetDungeonDifficulty()
							== DUNGEON_DIFFICULTY_NORMAL) {
						// dungeon in normal mode accepted
						if (!achievIdForDungeon[j][1])
							break; // for
					} else {
						// dungeon in heroic mode accepted
						if (!achievIdForDungeon[j][3])
							break; // for
					}

					found = true;
					break; // for
				}
			}
			if (!found)
				continue;

			//FIXME: work only for instances where max == min for players
			if (((InstanceMap*) map)->GetMaxPlayers()
					!= achievementCriteria->death_in_dungeon.manLimit)
				continue;
			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			if (miscvalue1
					!= achievementCriteria->killed_by_creature.creatureEntry)
				continue;
			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;

			// if team check required: must kill by opposition faction
			if (achievement->ID == 318 && miscvalue2 == GetPlayer()->GetTeam())
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING: {
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;

			// those requirements couldn't be found in the dbc
			AchievementCriteriaDataSet const* data =
					sAchievementMgr->GetCriteriaDataSet(achievementCriteria);
			if (!data || !data->Meets(GetPlayer(), unit))
				continue;

			// miscvalue1 is the ingame fallheight*100 as stored in dbc
			SetCriteriaProgress(achievementCriteria, miscvalue1);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			if (miscvalue2 != achievementCriteria->death_from.type)
				continue;
			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: {
			// if miscvalues != 0, it contains the questID.
			if (miscvalue1) {
				if (miscvalue1 != achievementCriteria->complete_quest.questID)
					continue;
			} else {
				// login case.
				if (!GetPlayer()->GetQuestRewardStatus(
						achievementCriteria->complete_quest.questID))
					continue;
			}

			// exist many achievements with this criteria, use at this moment hardcoded check to skil simple case
			switch (achievement->ID) {
			case 31:
			case 1275:
			case 1276:
			case 1277:
			case 1282:
			case 1789: {
				// those requirements couldn't be found in the dbc
				AchievementCriteriaDataSet const* data =
						sAchievementMgr->GetCriteriaDataSet(
								achievementCriteria);
				if (!data || !data->Meets(GetPlayer(), unit))
					continue;
				break;
			}
			default:
				break;
			}

			SetCriteriaProgress(achievementCriteria, 1);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
		case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: {
			if (!miscvalue1
					|| miscvalue1
							!= achievementCriteria->be_spell_target.spellID)
				continue;

			// those requirements couldn't be found in the dbc
			AchievementCriteriaDataSet const* data =
					sAchievementMgr->GetCriteriaDataSet(achievementCriteria);
			if (!data)
				continue;

			if (!data->Meets(GetPlayer(), unit))
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
		case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: {
			if (!miscvalue1
					|| miscvalue1 != achievementCriteria->cast_spell.spellID)
				continue;

			// those requirements couldn't be found in the dbc
			AchievementCriteriaDataSet const* data =
					sAchievementMgr->GetCriteriaDataSet(achievementCriteria);
			if (!data)
				continue;

			if (!data->Meets(GetPlayer(), unit))
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
			if (miscvalue1
					&& miscvalue1 != achievementCriteria->learn_spell.spellID)
				continue;

			if (GetPlayer()->HasSpell(achievementCriteria->learn_spell.spellID))
				SetCriteriaProgress(achievementCriteria, 1);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: {
			// miscvalue1=loot_type (note: 0 = LOOT_CORPSE and then it ignored)
			// miscvalue2=count of item loot
			if (!miscvalue1 || !miscvalue2)
				continue;
			if (miscvalue1 != achievementCriteria->loot_type.lootType)
				continue;

			// zone specific
			if (achievementCriteria->loot_type.lootTypeCount == 1) {
				// those requirements couldn't be found in the dbc
				AchievementCriteriaDataSet const* data =
						sAchievementMgr->GetCriteriaDataSet(
								achievementCriteria);
				if (!data || !data->Meets(GetPlayer(), unit))
					continue;
			}

			SetCriteriaProgress(achievementCriteria, miscvalue2,
					PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
			// speedup for non-login case
			if (miscvalue1
					&& achievementCriteria->own_item.itemID != miscvalue1)
				continue;
			SetCriteriaProgress(
					achievementCriteria,
					GetPlayer()->GetItemCount(
							achievementCriteria->own_item.itemID, true));
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
			// miscvalue1 contains the personal rating
			if (!miscvalue1) // no update at login
				continue;

			// additional requirements
			if (achievementCriteria->additionalRequirements[0].additionalRequirement_type
					== ACHIEVEMENT_CRITERIA_CONDITION_NO_LOSE) {
				// those requirements couldn't be found in the dbc
				AchievementCriteriaDataSet const* data =
						sAchievementMgr->GetCriteriaDataSet(
								achievementCriteria);
				if (!data || !data->Meets(GetPlayer(), unit, miscvalue1)) {
					// reset the progress as we have a win without the requirement.
					SetCriteriaProgress(achievementCriteria, 0);
					continue;
				}
			}

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			if (achievementCriteria->use_item.itemID != miscvalue1)
				continue;
			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
			// You _have_ to loot that item, just owning it when logging in does _not_ count!
			if (!miscvalue1)
				continue;
			if (miscvalue1 != achievementCriteria->own_item.itemID)
				continue;
			SetCriteriaProgress(achievementCriteria, miscvalue2,
					PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA: {
			WorldMapOverlayEntry const* worldOverlayEntry =
					sWorldMapOverlayStore.LookupEntry(
							achievementCriteria->explore_area.areaReference);
			if (!worldOverlayEntry)
				break;

			bool matchFound = false;
			for (int j = 0; j < MAX_WORLD_MAP_OVERLAY_AREA_IDX; ++j) {
				uint32 area_id = worldOverlayEntry->areatableID[j];
				if (!area_id) // array have 0 only in empty tail
					break;

				int32 exploreFlag = GetAreaFlagByAreaID(area_id);
				if (exploreFlag < 0)
					continue;

				uint32 playerIndexOffset = uint32(exploreFlag) / 32;
				uint32 mask = 1 << (uint32(exploreFlag) % 32);

				if (GetPlayer()->GetUInt32Value(
						PLAYER_EXPLORED_ZONES_1 + playerIndexOffset) & mask) {
					matchFound = true;
					break;
				}
			}

			if (matchFound)
				SetCriteriaProgress(achievementCriteria, 1);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
			SetCriteriaProgress(achievementCriteria,
					GetPlayer()->GetBankBagSlotCount());
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION: {
			// skip faction check only at loading
			if (miscvalue1
					&& miscvalue1
							!= achievementCriteria->gain_reputation.factionID)
				continue;

			int32 reputation = GetPlayer()->GetReputationMgr().GetReputation(
					achievementCriteria->gain_reputation.factionID);
			if (reputation > 0)
				SetCriteriaProgress(achievementCriteria, reputation);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION: {
			SetCriteriaProgress(achievementCriteria,
					GetPlayer()->GetReputationMgr().GetExaltedFactionCount());
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP: {
			// skip for login case
			if (!miscvalue1)
				continue;
			SetCriteriaProgress(achievementCriteria, 1);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: {
			// miscvalue1 = itemid
			// miscvalue2 = itemSlot
			if (!miscvalue1)
				continue;

			if (miscvalue2 != achievementCriteria->equip_epic_item.itemSlot)
				continue;

			// check item level and quality via achievement_criteria_data
			AchievementCriteriaDataSet const* data =
					sAchievementMgr->GetCriteriaDataSet(achievementCriteria);
			if (!data || !data->Meets(GetPlayer(), 0, miscvalue1))
				continue;

			SetCriteriaProgress(achievementCriteria, 1);
			break;
		}

		case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
		case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT: {
			// miscvalue1 = itemid
			// miscvalue2 = diced value
			if (!miscvalue1)
				continue;
			if (miscvalue2 != achievementCriteria->roll_greed_on_loot.rollValue)
				continue;

			ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(
					miscvalue1);
			if (!pProto)
				continue;

			// check item level via achievement_criteria_data
			AchievementCriteriaDataSet const* data =
					sAchievementMgr->GetCriteriaDataSet(achievementCriteria);
			if (!data || !data->Meets(GetPlayer(), 0, pProto->ItemLevel))
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: {
			// miscvalue1 = emote
			if (!miscvalue1)
				continue;
			if (miscvalue1 != achievementCriteria->do_emote.emoteID)
				continue;
			if (achievementCriteria->do_emote.count) {
				// those requirements couldn't be found in the dbc
				AchievementCriteriaDataSet const* data =
						sAchievementMgr->GetCriteriaDataSet(
								achievementCriteria);
				if (!data || !data->Meets(GetPlayer(), unit))
					continue;
			}

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
		case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE: {
			if (!miscvalue1)
				continue;

			if (achievementCriteria->additionalRequirements[0].additionalRequirement_type
					== ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP) {
				if (GetPlayer()->GetMapId()
						!= achievementCriteria->additionalRequirements[0].additionalRequirement_value)
					continue;

				// map specific case (BG in fact) expected player targeted damage/heal
				if (!unit || unit->GetTypeId() != TYPEID_PLAYER)
					continue;
			}

			SetCriteriaProgress(achievementCriteria, miscvalue1,
					PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
			// miscvalue1 = item_id
			if (!miscvalue1)
				continue;
			if (miscvalue1 != achievementCriteria->equip_item.itemID)
				continue;

			SetCriteriaProgress(achievementCriteria, 1);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
			// miscvalue1 = go entry
			if (!miscvalue1)
				continue;
			if (miscvalue1 != achievementCriteria->use_gameobject.goEntry)
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
			if (!miscvalue1)
				continue;
			if (miscvalue1 != achievementCriteria->fish_in_gameobject.goEntry)
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS: {
			if (miscvalue1
					&& miscvalue1
							!= achievementCriteria->learn_skillline_spell.skillLine)
				continue;

			uint32 spellCount = 0;
			for (PlayerSpellMap::const_iterator spellIter =
					GetPlayer()->GetSpellMap().begin();
					spellIter != GetPlayer()->GetSpellMap().end();
					++spellIter) {
				SkillLineAbilityMapBounds bounds =
						sSpellMgr->GetSkillLineAbilityMapBounds(
								spellIter->first);
				for (SkillLineAbilityMap::const_iterator skillIter =
						bounds.first; skillIter != bounds.second; ++skillIter) {
					if (skillIter->second->skillId
							== achievementCriteria->learn_skillline_spell.skillLine)
						spellCount++;
				}
			}
			SetCriteriaProgress(achievementCriteria, spellCount);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;

			if (achievementCriteria->win_duel.duelCount) {
				// those requirements couldn't be found in the dbc
				AchievementCriteriaDataSet const* data =
						sAchievementMgr->GetCriteriaDataSet(
								achievementCriteria);
				if (!data)
					continue;

				if (!data->Meets(GetPlayer(), unit))
					continue;
			}

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
			SetCriteriaProgress(achievementCriteria,
					GetPlayer()->GetReputationMgr().GetReveredFactionCount());
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
			SetCriteriaProgress(achievementCriteria,
					GetPlayer()->GetReputationMgr().GetHonoredFactionCount());
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
			SetCriteriaProgress(achievementCriteria,
					GetPlayer()->GetReputationMgr().GetVisibleFactionCount());
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
		case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM: {
			// AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case
			if (!miscvalue1)
				continue;
			ItemPrototype const* proto = ObjectMgr::GetItemPrototype(
					miscvalue1);
			if (!proto || proto->Quality < ITEM_QUALITY_EPIC)
				continue;
			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE: {
			if (miscvalue1
					&& miscvalue1
							!= achievementCriteria->learn_skill_line.skillLine)
				continue;

			uint32 spellCount = 0;
			for (PlayerSpellMap::const_iterator spellIter =
					GetPlayer()->GetSpellMap().begin();
					spellIter != GetPlayer()->GetSpellMap().end();
					++spellIter) {
				SkillLineAbilityMapBounds bounds =
						sSpellMgr->GetSkillLineAbilityMapBounds(
								spellIter->first);
				for (SkillLineAbilityMap::const_iterator skillIter =
						bounds.first; skillIter != bounds.second; ++skillIter)
					if (skillIter->second->skillId
							== achievementCriteria->learn_skill_line.skillLine)
						spellCount++;
			}
			SetCriteriaProgress(achievementCriteria, spellCount);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
			SetCriteriaProgress(
					achievementCriteria,
					GetPlayer()->GetUInt32Value(
							PLAYER_FIELD_LIFETIME_HONORBALE_KILLS));
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
			if (!miscvalue1
					|| miscvalue1 != achievementCriteria->hk_class.classID)
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
			if (!miscvalue1
					|| miscvalue1 != achievementCriteria->hk_race.raceID)
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
			SetCriteriaProgress(achievementCriteria, GetPlayer()->GetMoney(),
					PROGRESS_HIGHEST);
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS: {
			if (!miscvalue1) {
				uint32 points = 0;
				for (CompletedAchievementMap::iterator itr =
						m_completedAchievements.begin();
						itr != m_completedAchievements.end(); ++itr)
					if (AchievementEntry const* pAchievement = sAchievementStore.LookupEntry(itr->first))
						points += pAchievement->points;
				SetCriteriaProgress(achievementCriteria, points, PROGRESS_SET);
			} else
				SetCriteriaProgress(achievementCriteria, miscvalue1,
						PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE: {
			if (!miscvalue1
					|| miscvalue1
							!= achievementCriteria->bg_objective.objectiveId)
				continue;

			// those requirements couldn't be found in the dbc
			AchievementCriteriaDataSet const* data =
					sAchievementMgr->GetCriteriaDataSet(achievementCriteria);
			if (!data || !data->Meets(GetPlayer(), unit))
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
		case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL: {
			// skip login update
			if (!miscvalue1)
				continue;
			// those requirements couldn't be found in the dbc
			AchievementCriteriaDataSet const* data =
					sAchievementMgr->GetCriteriaDataSet(achievementCriteria);
			if (!data || !data->Meets(GetPlayer(), unit))
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA: {
			if (!miscvalue1
					|| miscvalue1
							!= achievementCriteria->honorable_kill_at_area.areaID)
				continue;

			SetCriteriaProgress(achievementCriteria, 1, PROGRESS_ACCUMULATE);
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
		case ACHIEVEMENT_CRITERIA_TYPE_REACH_TEAM_RATING: {
			uint32 reqTeamType =
					type == ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING ?
							achievementCriteria->highest_team_rating.teamtype :
							achievementCriteria->reach_team_rating.teamtype;

			if (miscvalue1) {
				if (miscvalue2 != reqTeamType)
					continue;

				SetCriteriaProgress(achievementCriteria, miscvalue1,
						PROGRESS_HIGHEST);
			} else // login case
			{
				for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT;
						++arena_slot)
					if (uint32 arena_team_id = GetPlayer()->GetArenaTeamId(arena_slot))
						if (ArenaTeam * at = sObjectMgr->GetArenaTeamById(
								arena_team_id))
							if (at->GetType() == reqTeamType) {
								SetCriteriaProgress(achievementCriteria,
										at->GetStats().Rating,
										PROGRESS_HIGHEST);
								break;
							}
			}

			break;
		}
			// std case: not exist in DBC, not triggered in code as result
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALTH:
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_SPELLPOWER:
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_ARMOR:
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_POWER:
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_STAT:
		case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_RATING:
			break;
			// FIXME: not triggered in code as result, need to implement
		case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID:
		case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
		case ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA:
		case ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK:
		case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
		case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE:
		case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE:
		case ACHIEVEMENT_CRITERIA_TYPE_TOTAL:
			break; // Not implemented yet :(
		}

		if (IsCompletedCriteria(achievementCriteria, achievement))
			CompletedCriteriaFor(achievement);

		// check again the completeness for SUMM and REQ COUNT achievements,
		// as they don't depend on the completed criteria but on the sum of the progress of each individual criteria
		if (achievement->flags & ACHIEVEMENT_FLAG_SUMM) {
			if (IsCompletedAchievement(achievement))
				CompletedAchievement(achievement);
		}

		if (AchievementEntryList const* achRefList = sAchievementMgr->GetAchievementByReferencedId(achievement->ID)) {
			for (AchievementEntryList::const_iterator itr = achRefList->begin();
					itr != achRefList->end(); ++itr)
				if (IsCompletedAchievement(*itr))
					CompletedAchievement(*itr);
		}
	}
}

static const uint32 achievIdByClass[MAX_CLASSES] = { 0, 459, 465, 462, 458, 464,
		461, 467, 460, 463, 0, 466 };
static const uint32 achievIdByRace[MAX_RACES] = { 0, 1408, 1410, 1407, 1409,
		1413, 1411, 1404, 1412, 0, 1405, 1406 };

bool AchievementMgr::IsCompletedCriteria(
		AchievementCriteriaEntry const* achievementCriteria,
		AchievementEntry const* achievement) {
	// counter can never complete
	if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
		return false;

	if (achievement->flags
			& (ACHIEVEMENT_FLAG_REALM_FIRST_REACH
					| ACHIEVEMENT_FLAG_REALM_FIRST_KILL)) {
		// someone on this realm has already completed that achievement
		if (sAchievementMgr->IsRealmCompleted(achievement))
			return false;
	}

	CriteriaProgress const* progress = GetCriteriaProgress(achievementCriteria);
	if (!progress)
		return false;

	switch (achievementCriteria->requiredType) {
	case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
		return progress->counter >= achievementCriteria->win_bg.winCount;
	case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
		return progress->counter
				>= achievementCriteria->kill_creature.creatureCount;
	case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL: {
		// skip wrong class achievements
		for (int i = 1; i < MAX_CLASSES; ++i)
			if (achievIdByClass[i] == achievement->ID
					&& i != GetPlayer()->getClass())
				return false;

		// skip wrong race achievements
		for (int i = 1; i < MAX_RACES; ++i)
			if (achievIdByRace[i] == achievement->ID
					&& i != GetPlayer()->getRace())
				return false;

		// appropriate class/race or not class/race specific
		return progress->counter >= achievementCriteria->reach_level.level;
	}
	case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
		return progress->counter
				>= achievementCriteria->reach_skill_level.skillLevel;
	case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
		return progress->counter >= 1;
	case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
		return progress->counter
				>= achievementCriteria->complete_quest_count.totalQuestCount;
	case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
		return progress->counter
				>= achievementCriteria->complete_daily_quest_daily.numberOfDays;
	case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
		return progress->counter
				>= achievementCriteria->complete_quests_in_zone.questCount;
	case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
	case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
		return progress->counter >= achievementCriteria->healing_done.count;
	case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
		return progress->counter
				>= achievementCriteria->complete_daily_quest.questCount;
	case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
		return progress->counter
				>= achievementCriteria->fall_without_dying.fallHeight;
	case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
		return progress->counter >= 1;
	case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
	case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
		return progress->counter
				>= achievementCriteria->be_spell_target.spellCount;
	case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
	case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
		return progress->counter >= achievementCriteria->cast_spell.castCount;
	case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
		return progress->counter
				>= achievementCriteria->bg_objective.completeCount;
	case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
		return progress->counter
				>= achievementCriteria->honorable_kill_at_area.killCount;
	case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
		return progress->counter >= 1;
	case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
		return progress->counter
				>= achievementCriteria->honorable_kill.killCount;
	case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
		return progress->counter >= achievementCriteria->own_item.itemCount;
	case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
		return progress->counter >= achievementCriteria->win_rated_arena.count;
	case ACHIEVEMENT_CRITERIA_TYPE_REACH_TEAM_RATING:
		return progress->counter
				>= achievementCriteria->reach_team_rating.teamrating;
	case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
		return progress->counter
				>= (achievementCriteria->learn_skill_level.skillLevel * 75);
	case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
		return progress->counter >= achievementCriteria->use_item.itemCount;
	case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
		return progress->counter >= achievementCriteria->loot_item.itemCount;
	case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
		return progress->counter >= 1;
	case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
		return progress->counter
				>= achievementCriteria->buy_bank_slot.numberOfSlots;
	case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
		return progress->counter
				>= achievementCriteria->gain_reputation.reputationAmount;
	case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
		return progress->counter
				>= achievementCriteria->gain_exalted_reputation.numberOfExaltedFactions;
	case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
		return progress->counter
				>= achievementCriteria->visit_barber.numberOfVisits;
	case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
		return progress->counter >= achievementCriteria->equip_epic_item.count;
	case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
	case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
		return progress->counter
				>= achievementCriteria->roll_greed_on_loot.count;
	case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
		return progress->counter >= achievementCriteria->hk_class.count;
	case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
		return progress->counter >= achievementCriteria->hk_race.count;
	case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
		return progress->counter >= achievementCriteria->do_emote.count;
	case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
		return progress->counter >= achievementCriteria->equip_item.count;
	case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
		return progress->counter
				>= achievementCriteria->quest_reward_money.goldInCopper;
	case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
		return progress->counter >= achievementCriteria->loot_money.goldInCopper;
	case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
		return progress->counter >= achievementCriteria->use_gameobject.useCount;
	case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
		return progress->counter
				>= achievementCriteria->special_pvp_kill.killCount;
	case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
		return progress->counter
				>= achievementCriteria->fish_in_gameobject.lootCount;
	case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
		return progress->counter
				>= achievementCriteria->learn_skillline_spell.spellCount;
	case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
		return progress->counter >= achievementCriteria->win_duel.duelCount;
	case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
		return progress->counter >= achievementCriteria->loot_type.lootTypeCount;
	case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
		return progress->counter
				>= achievementCriteria->learn_skill_line.spellCount;
	case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
		return progress->counter >= 9000;
	case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
		return progress->counter
				>= achievementCriteria->use_lfg.dungeonsComplete;
		// handle all statistic-only criteria here
	case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
	case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
	case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
	case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
	case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
	case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
	case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
	case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
	case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
	case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
	case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
	case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
	case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
	case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
	case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:
	case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
	case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
	case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD:
	case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
	case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS:
	case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
	case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
	case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
	case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
	case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
	case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
	case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
	case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALTH:
	case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_SPELLPOWER:
	case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_ARMOR:
	case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
	case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
	case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
	default:
		break;
	}
	return false;
}

void AchievementMgr::CompletedCriteriaFor(AchievementEntry const* achievement) {
	// counter can never complete
	if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
		return;

	// already completed and stored
	if (HasAchieved(achievement))
		return;

	if (IsCompletedAchievement(achievement))
		CompletedAchievement(achievement);
}

bool AchievementMgr::IsCompletedAchievement(AchievementEntry const* entry) {
	// counter can never complete
	if (entry->flags & ACHIEVEMENT_FLAG_COUNTER)
		return false;

	// for achievement with referenced achievement criterias get from referenced and counter from self
	uint32 achievmentForTestId =
			entry->refAchievement ? entry->refAchievement : entry->ID;
	uint32 achievmentForTestCount = entry->count;

	AchievementCriteriaEntryList const* cList =
			sAchievementMgr->GetAchievementCriteriaByAchievement(
					achievmentForTestId);
	if (!cList)
		return false;
	uint32 count = 0;

	// For SUMM achievements, we have to count the progress of each criteria of the achievement.
	// Oddly, the target count is NOT countained in the achievement, but in each individual criteria
	if (entry->flags & ACHIEVEMENT_FLAG_SUMM) {
		for (AchievementCriteriaEntryList::const_iterator itr = cList->begin();
				itr != cList->end(); ++itr) {
			AchievementCriteriaEntry const* criteria = *itr;

			CriteriaProgress const* progress = GetCriteriaProgress(criteria);
			if (!progress)
				continue;

			count += progress->counter;

			// for counters, field4 contains the main count requirement
			if (count >= criteria->raw.count)
				return true;
		}
		return false;
	}

	// Default case - need complete all or
	bool completed_all = true;
	for (AchievementCriteriaEntryList::const_iterator itr = cList->begin();
			itr != cList->end(); ++itr) {
		AchievementCriteriaEntry const* criteria = *itr;

		bool completed = IsCompletedCriteria(criteria, entry);

		// found an uncompleted criteria, but DONT return false yet - there might be a completed criteria with ACHIEVEMENT_CRITERIA_COMPLETE_FLAG_ALL
		if (completed)
			++count;
		else
			completed_all = false;

		// completed as have req. count of completed criterias
		if (achievmentForTestCount > 0 && achievmentForTestCount <= count)
			return true;
	}

	// all criterias completed requirement
	if (completed_all && achievmentForTestCount == 0)
		return true;

	return false;
}

CriteriaProgress* AchievementMgr::GetCriteriaProgress(
		AchievementCriteriaEntry const* entry) {
	CriteriaProgressMap::iterator iter = m_criteriaProgress.find(entry->ID);

	if (iter == m_criteriaProgress.end())
		return NULL;

	return &(iter->second);
}

void AchievementMgr::SetCriteriaProgress(AchievementCriteriaEntry const* entry,
		uint32 changeValue, ProgressType ptype) {
	// Don't allow to cheat - doing timed achievements without timer active
	TimedAchievementMap::iterator timedIter = m_timedAchievements.find(
			entry->ID);
	if (entry->timeLimit && timedIter == m_timedAchievements.end())
		return;

	sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS,
			"AchievementMgr::SetCriteriaProgress(%u, %u) for (GUID:%u)",
			entry->ID, changeValue, m_player->GetGUIDLow());

	CriteriaProgress* progress = GetCriteriaProgress(entry);
	if (!progress) {
		// not create record for 0 counter but allow it for timed achievements
		// we will need to send 0 progress to client to start the timer
		if (changeValue == 0 && !entry->timeLimit)
			return;

		progress = &m_criteriaProgress[entry->ID];
		progress->counter = changeValue;
	} else {
		uint32 newValue = 0;
		switch (ptype) {
		case PROGRESS_SET:
			newValue = changeValue;
			break;
		case PROGRESS_ACCUMULATE: {
			// avoid overflow
			uint32 max_value = std::numeric_limits < uint32 > ::max();
			newValue =
					max_value - progress->counter > changeValue ?
							progress->counter + changeValue : max_value;
			break;
		}
		case PROGRESS_HIGHEST:
			newValue =
					progress->counter < changeValue ?
							changeValue : progress->counter;
			break;
		}

		// not update (not mark as changed) if counter will have same value
		if (progress->counter == newValue && !entry->timeLimit)
			return;

		progress->counter = newValue;
	}

	progress->changed = true;
	progress->date = time(NULL); // set the date to the latest update.

	uint32 timeElapsed = 0;
	bool timedCompleted = false;

	if (entry->timeLimit) {
		// has to exist else we wouldn't be here
		timedCompleted = IsCompletedCriteria(entry,
				sAchievementStore.LookupEntry(entry->referredAchievement));
		// Client expects this in packet
		timeElapsed = entry->timeLimit - (timedIter->second / IN_MILLISECONDS);

		// Remove the timer, we wont need it anymore
		if (timedCompleted)
			m_timedAchievements.erase(timedIter);
	}

	SendCriteriaUpdate(entry, progress, timeElapsed, timedCompleted);
}

void AchievementMgr::RemoveCriteriaProgress(
		const AchievementCriteriaEntry *entry) {
	CriteriaProgressMap::iterator criteriaProgress = m_criteriaProgress.find(
			entry->ID);
	if (criteriaProgress == m_criteriaProgress.end())
		return;

	WorldPacket data(SMSG_CRITERIA_DELETED, 4);
	data << uint32(entry->ID);
	m_player->SendDirectMessage(&data);

	m_criteriaProgress.erase(criteriaProgress);
}

void AchievementMgr::UpdateTimedAchievements(uint32 timeDiff) {
	if (!m_timedAchievements.empty()) {
		for (TimedAchievementMap::iterator itr = m_timedAchievements.begin();
				itr != m_timedAchievements.end();) {
			// Time is up, remove timer and reset progress
			if (itr->second <= timeDiff) {
				AchievementCriteriaEntry const *entry =
						sAchievementCriteriaStore.LookupEntry(itr->first);
				RemoveCriteriaProgress(entry);
				m_timedAchievements.erase(itr++);
			} else {
				itr->second -= timeDiff;
				++itr;
			}
		}
	}
}

void AchievementMgr::StartTimedAchievement(AchievementCriteriaTimedTypes type,
		uint32 entry, uint32 timeLost /*= 0*/) {
	AchievementCriteriaEntryList const& achievementCriteriaList =
			sAchievementMgr->GetTimedAchievementCriteriaByType(type);
	for (AchievementCriteriaEntryList::const_iterator i =
			achievementCriteriaList.begin(); i != achievementCriteriaList.end();
			++i) {
		if ((*i)->timerStartEvent != entry)
			continue;

		AchievementEntry const *achievement = sAchievementStore.LookupEntry(
				(*i)->referredAchievement);
		if (m_timedAchievements.find((*i)->ID) == m_timedAchievements.end()
				&& !IsCompletedCriteria(*i, achievement)) {
			// Start the timer
			if ((*i)->timeLimit * IN_MILLISECONDS > timeLost) {
				m_timedAchievements[(*i)->ID] = (*i)->timeLimit
						* IN_MILLISECONDS - timeLost;

				// and at client too
				SetCriteriaProgress(*i, 0, PROGRESS_SET);
			}
		}
	}
}

void AchievementMgr::RemoveTimedAchievement(AchievementCriteriaTimedTypes type,
		uint32 entry) {
	AchievementCriteriaEntryList const& achievementCriteriaList =
			sAchievementMgr->GetTimedAchievementCriteriaByType(type);
	for (AchievementCriteriaEntryList::const_iterator i =
			achievementCriteriaList.begin(); i != achievementCriteriaList.end();
			++i) {
		if ((*i)->timerStartEvent != entry)
			continue;

		TimedAchievementMap::iterator timedIter = m_timedAchievements.find(
				(*i)->ID);
		// We don't have timer for this achievement
		if (timedIter == m_timedAchievements.end())
			continue;

		// remove progress
		RemoveCriteriaProgress(*i);

		// Remove the timer
		m_timedAchievements.erase(timedIter);
	}
}

void AchievementMgr::CompletedAchievement(AchievementEntry const* achievement,
		bool ignoreGMAllowAchievementConfig) {
	sLog->outDetail("AchievementMgr::CompletedAchievement(%u)",
			achievement->ID);

	if (m_player->GetSession()->GetSecurity()
			> AccountTypes(
					sWorld->getIntConfig(CONFIG_GM_LEVEL_ALLOW_ACHIEVEMENTS))
			&& !ignoreGMAllowAchievementConfig)
		return;

	if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER
			|| HasAchieved(achievement))
		return;

	CompletedAchievementData& ca = m_completedAchievements[achievement->ID];
	ca.date = time(NULL);
	ca.changed = true;

	if (AchievementEntry const* pAchievement = sAchievementStore.LookupEntry(achievement->ID))
		achievementPoints += pAchievement->points;

	SendAchievementEarned(achievement);

	// don't insert for ACHIEVEMENT_FLAG_REALM_FIRST_KILL since otherwise only the first group member would reach that achievement
	// TODO: where do set this instead?
	if (!(achievement->flags & ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
		sAchievementMgr->SetRealmCompleted(achievement);

	UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT);
	UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS,
			achievement->points);

	// reward items and titles if any
	AchievementReward const* reward = sAchievementMgr->GetAchievementReward(
			achievement);

	// no rewards
	if (!reward)
		return;

	// titles
	if (uint32 titleId = reward->titleId[GetPlayer()->GetTeam() == ALLIANCE ? 0 : 1])
		if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId))
			GetPlayer()->SetTitle(titleEntry);

	// mail
	if (reward->sender) {
		Item* item =
				reward->itemId ?
						Item::CreateItem(reward->itemId, 1, GetPlayer()) : NULL;

		int loc_idx = GetPlayer()->GetSession()->GetSessionDbLocaleIndex();

		// subject and text
		std::string subject = reward->subject;
		std::string text = reward->text;
		if (loc_idx >= 0) {
			if (AchievementRewardLocale const* loc = sAchievementMgr->GetAchievementRewardLocale(achievement)) {
				sObjectMgr->GetLocaleString(loc->subject, loc_idx, subject);
				sObjectMgr->GetLocaleString(loc->text, loc_idx, text);
			}
		}

		MailDraft draft(subject, text);

		SQLTransaction trans = CharacterDatabase.BeginTransaction();
		if (item) {
			// save new item before send
			item->SaveToDB(trans); // save for prevent lost at next mail load, if send fail then item will deleted

			// item
			draft.AddItem(item);
		}

		draft.SendMailTo(trans, GetPlayer(),
				MailSender(MAIL_CREATURE, reward->sender));
		CharacterDatabase.CommitTransaction(trans);
	}
}

void AchievementMgr::SendAllAchievementData() {
	uint32 criterias = m_criteriaProgress.size();
	uint32 achievements = m_completedAchievements.size();
	// 2 is flag count, 8 is bits in byte
	uint32 flagBytesCount = uint32(ceil(float(criterias) * 2.0f / 8.0f));

	// since we don't know the exact size of the packed GUIDs this is just an approximation
	WorldPacket data(
			SMSG_ALL_ACHIEVEMENT_DATA,
			4 + criterias * (8 + 4 + 4 + 8) + 8 + 4 + achievements * (4 + 4 + 4)
					+ flagBytesCount);

	data << uint32(achievements);
	data << uint32(criterias);

	for (CompletedAchievementMap::const_iterator iter =
			m_completedAchievements.begin();
			iter != m_completedAchievements.end(); ++iter)
		data << uint32(iter->first);
	for (CompletedAchievementMap::const_iterator iter =
			m_completedAchievements.begin();
			iter != m_completedAchievements.end(); ++iter)
		data << uint32(secsToTimeBitFields(iter->second.date));

	for (CriteriaProgressMap::const_iterator iter = m_criteriaProgress.begin();
			iter != m_criteriaProgress.end(); ++iter)
		data << uint64(iter->second.counter);

	time_t now = time(NULL);
	for (CriteriaProgressMap::const_iterator iter = m_criteriaProgress.begin();
			iter != m_criteriaProgress.end(); ++iter)
		data << uint32(now - iter->second.date);
	for (CriteriaProgressMap::const_iterator iter = m_criteriaProgress.begin();
			iter != m_criteriaProgress.end(); ++iter)
		data << uint32(secsToTimeBitFields(iter->second.date));
	for (uint32 i = 0; i < criterias; ++i)
		data.append(GetPlayer()->GetPackGUID());
	for (CriteriaProgressMap::const_iterator iter = m_criteriaProgress.begin();
			iter != m_criteriaProgress.end(); ++iter)
		data << uint32(now - iter->second.date);

	for (uint32 i = 0; i < flagBytesCount; ++i)
		data << uint8(0);

	for (CriteriaProgressMap::const_iterator iter = m_criteriaProgress.begin();
			iter != m_criteriaProgress.end(); ++iter)
		data << uint32(iter->first);

	GetPlayer()->GetSession()->SendPacket(&data);
}

void AchievementMgr::SendRespondInspectAchievements(Player* player) {
	uint32 criterias = m_criteriaProgress.size();
	uint32 achievements = m_completedAchievements.size();
	// 2 is flag count, 8 is bits in byte
	uint32 flagBytesCount = uint32(ceil(float(criterias) * 2.0f / 8.0f));

	// since we don't know the exact size of the packed GUIDs this is just an approximation
	WorldPacket data(
			SMSG_RESPOND_INSPECT_ACHIEVEMENTS,
			4 + criterias * (8 + 4 + 4 + 8) + 8 + 4 + achievements * (4 + 4 + 4)
					+ flagBytesCount);

	data << uint32(criterias);

	for (CriteriaProgressMap::const_iterator iter = m_criteriaProgress.begin();
			iter != m_criteriaProgress.end(); ++iter)
		data << uint64(iter->second.counter);
	for (CriteriaProgressMap::const_iterator iter = m_criteriaProgress.begin();
			iter != m_criteriaProgress.end(); ++iter)
		data << uint32(iter->second.date);
	for (CriteriaProgressMap::const_iterator iter = m_criteriaProgress.begin();
			iter != m_criteriaProgress.end(); ++iter)
		data << uint32(iter->first);

	data.append(GetPlayer()->GetPackGUID());

	for (uint32 i = 0; i < criterias; ++i)
		data.append(GetPlayer()->GetPackGUID());

	data << uint32(achievements);

	for (CompletedAchievementMap::const_iterator iter =
			m_completedAchievements.begin();
			iter != m_completedAchievements.end(); ++iter)
		data << uint32(iter->first);
	for (CompletedAchievementMap::const_iterator iter =
			m_completedAchievements.begin();
			iter != m_completedAchievements.end(); ++iter)
		data << uint32(secsToTimeBitFields(iter->second.date));

	for (uint32 i = 0; i < flagBytesCount; ++i)
		data << uint8(0);

	for (CompletedAchievementMap::const_iterator iter =
			m_completedAchievements.begin();
			iter != m_completedAchievements.end(); ++iter)
		data << uint32(secsToTimeBitFields(iter->second.date));

	player->GetSession()->SendPacket(&data);
}

bool AchievementMgr::HasAchieved(AchievementEntry const* achievement) const {
	return m_completedAchievements.find(achievement->ID)
			!= m_completedAchievements.end();
}

//==========================================================
AchievementCriteriaEntryList const& AchievementGlobalMgr::GetAchievementCriteriaByType(
		AchievementCriteriaTypes type) {
	return m_AchievementCriteriasByType[type];
}

AchievementCriteriaEntryList const& AchievementGlobalMgr::GetTimedAchievementCriteriaByType(
		AchievementCriteriaTimedTypes type) {
	return m_AchievementCriteriasByTimedType[type];
}

void AchievementGlobalMgr::LoadAchievementCriteriaList() {
	uint32 oldMSTime = getMSTime();

	if (sAchievementCriteriaStore.GetNumRows() == 0) {
		sLog->outErrorDb(">> Loaded 0 achievement criteria.");
		sLog->outString();
		return;
	}

	for (uint32 entryId = 0; entryId < sAchievementCriteriaStore.GetNumRows();
			++entryId) {
		AchievementCriteriaEntry const* criteria =
				sAchievementCriteriaStore.LookupEntry(entryId);
		if (!criteria)
			continue;

		m_AchievementCriteriasByType[criteria->requiredType].push_back(
				criteria);
		m_AchievementCriteriaListByAchievement[criteria->referredAchievement].push_back(
				criteria);

		if (criteria->timeLimit)
			m_AchievementCriteriasByTimedType[criteria->timedType].push_back(
					criteria);
	}

	sLog->outString(">> Loaded %lu achievement criteria in %u ms",
			(unsigned long) m_AchievementCriteriasByType->size(),
			GetMSTimeDiffToNow(oldMSTime));
	sLog->outString();
}

void AchievementGlobalMgr::LoadAchievementReferenceList() {
	uint32 oldMSTime = getMSTime();

	if (sAchievementStore.GetNumRows() == 0) {
		sLog->outString(">> Loaded 0 achievement references.");
		sLog->outString();
		return;
	}

	uint32 count = 0;
	for (uint32 entryId = 0; entryId < sAchievementStore.GetNumRows();
			++entryId) {
		AchievementEntry const* achievement = sAchievementStore.LookupEntry(
				entryId);
		if (!achievement || !achievement->refAchievement)
			continue;

		m_AchievementListByReferencedId[achievement->refAchievement].push_back(
				achievement);
		++count;
	}

	sLog->outString(">> Loaded %u achievement references in %u ms", count,
			GetMSTimeDiffToNow(oldMSTime));
	sLog->outString();
}

void AchievementGlobalMgr::LoadAchievementCriteriaData() {
	uint32 oldMSTime = getMSTime();

	m_criteriaDataMap.clear(); // need for reload case

	QueryResult result =
			WorldDatabase.Query(
					"SELECT criteria_id, type, value1, value2, ScriptName FROM achievement_criteria_data");

	if (!result) {
		sLog->outString(
				">> Loaded 0 additional achievement criteria data. DB table `achievement_criteria_data` is empty.");
		sLog->outString();
		return;
	}

	uint32 count = 0;
	do {
		Field *fields = result->Fetch();
		uint32 criteria_id = fields[0].GetUInt32();

		AchievementCriteriaEntry const* criteria =
				sAchievementCriteriaStore.LookupEntry(criteria_id);

		if (!criteria) {
			sLog->outErrorDb(
					"Table `achievement_criteria_data` has data for non-existing criteria (Entry: %u), ignore.",
					criteria_id);
			continue;
		}

		uint32 dataType = fields[1].GetUInt32();
		const char* scriptName = fields[4].GetCString();
		uint32 scriptId = 0;
		if (strcmp(scriptName, "")) // not empty
				{
			if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT)
				sLog->outErrorDb(
						"Table `achievement_criteria_data` has ScriptName set for non-scripted data type (Entry: %u, type %u), useless data.",
						criteria_id, dataType);
			else
				scriptId = sObjectMgr->GetScriptId(scriptName);
		}

		AchievementCriteriaData data(dataType, fields[2].GetUInt32(),
				fields[3].GetUInt32(), scriptId);

		if (!data.IsValid(criteria))
			continue;

		// this will allocate empty data set storage
		AchievementCriteriaDataSet& dataSet = m_criteriaDataMap[criteria_id];
		dataSet.SetCriteriaId(criteria_id);

		// add real data only for not NONE data types
		if (data.dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE)
			dataSet.Add(data);

		// counting data by and data types
		++count;
	} while (result->NextRow());

	// post loading checks
	for (uint32 entryId = 0; entryId < sAchievementCriteriaStore.GetNumRows();
			++entryId) {
		AchievementCriteriaEntry const* criteria =
				sAchievementCriteriaStore.LookupEntry(entryId);
		if (!criteria)
			continue;

		switch (criteria->requiredType) {
		case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: // any cases
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
			break; // any cases
		case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: {
			const AchievementEntry *achievement = sAchievementStore.LookupEntry(
					criteria->referredAchievement);
			if (!achievement)
				continue;

			// exist many achievements with this criteria, use at this moment hardcoded check to skil simple case
			switch (achievement->ID) {
			case 31:
			case 1275:
			case 1276:
			case 1277:
			case 1282:
			case 1789:
				break;
			default:
				continue;
			}
			break;
		}
		case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
			break; // any cases
		case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: // any cases
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL: // any cases
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: // need skip generic cases
			if (criteria->additionalRequirements[0].additionalRequirement_type
					!= ACHIEVEMENT_CRITERIA_CONDITION_NO_LOSE)
				continue;
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: // any cases
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
			break; // any cases
		case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
			break; // any cases
		case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: // need skip generic cases
			if (criteria->do_emote.count == 0)
				continue;
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
			break; // any cases
		case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: // skip statistics
			if (criteria->win_duel.duelCount == 0)
				continue;
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: // any cases
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: // need skip generic cases
			if (criteria->loot_type.lootTypeCount != 1)
				continue;
			break;
		case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
			break; // any cases
		case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
			break; // any cases
		case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL: // any cases
			break;
		default: // type not use DB data, ignore
			continue;
		}

		if (!GetCriteriaDataSet(criteria)
				&& !sDisableMgr->IsDisabledFor(
						DISABLE_TYPE_ACHIEVEMENT_CRITERIA, entryId, NULL))
			sLog->outErrorDb(
					"Table `achievement_criteria_data` does not have expected data for criteria (Entry: %u Type: %u) for achievement %u.",
					criteria->ID, criteria->requiredType,
					criteria->referredAchievement);
	}

	sLog->outString(
			">> Loaded %u additional achievement criteria data in %u ms", count,
			GetMSTimeDiffToNow(oldMSTime));
	sLog->outString();
}

void AchievementGlobalMgr::LoadCompletedAchievements() {
	uint32 oldMSTime = getMSTime();

	QueryResult result =
			CharacterDatabase.Query(
					"SELECT achievement FROM character_achievement GROUP BY achievement");

	if (!result) {
		sLog->outString(
				">> Loaded 0 completed achievements. DB table `character_achievement` is empty.");
		sLog->outString();
		return;
	}

	do {
		Field *fields = result->Fetch();

		uint32 achievement_id = fields[0].GetUInt32();
		if (!sAchievementStore.LookupEntry(achievement_id)) {
			// we will remove not existed achievement for all characters
			sLog->outError(
					"Non-existing achievement %u data removed from table `character_achievement`.",
					achievement_id);
			CharacterDatabase.PExecute(
					"DELETE FROM character_achievement WHERE achievement = %u",
					achievement_id);
			continue;
		}

		m_allCompletedAchievements.insert(achievement_id);
	} while (result->NextRow());

	sLog->outString(">> Loaded %lu completed achievements in %u ms",
			(unsigned long) m_allCompletedAchievements.size(),
			GetMSTimeDiffToNow(oldMSTime));
	sLog->outString();
}

void AchievementGlobalMgr::LoadRewards() {
	uint32 oldMSTime = getMSTime();

	m_achievementRewards.clear(); // need for reload case

	//                                                0      1        2        3     4       5        6
	QueryResult result =
			WorldDatabase.Query(
					"SELECT entry, title_A, title_H, item, sender, subject, text FROM achievement_reward");

	if (!result) {
		sLog->outErrorDb(
				">> Loaded 0 achievement rewards. DB table `achievement_reward` is empty.");
		sLog->outString();
		return;
	}

	uint32 count = 0;

	do {
		Field *fields = result->Fetch();
		uint32 entry = fields[0].GetUInt32();
		const AchievementEntry* pAchievement = sAchievementStore.LookupEntry(
				entry);
		if (!pAchievement) {
			sLog->outErrorDb(
					"Table `achievement_reward` has wrong achievement (Entry: %u), ignore",
					entry);
			continue;
		}

		AchievementReward reward;
		reward.titleId[0] = fields[1].GetUInt32();
		reward.titleId[1] = fields[2].GetUInt32();
		reward.itemId = fields[3].GetUInt32();
		reward.sender = fields[4].GetUInt32();
		reward.subject = fields[5].GetString();
		reward.text = fields[6].GetString();

		// must be title or mail at least
		if (!reward.titleId[0] && !reward.titleId[1] && !reward.sender) {
			sLog->outErrorDb(
					"Table `achievement_reward` (Entry: %u) not have title or item reward data, ignore.",
					entry);
			continue;
		}

		if (pAchievement->factionFlag == ACHIEVEMENT_FACTION_ANY
				&& ((reward.titleId[0] == 0) != (reward.titleId[1] == 0)))
			sLog->outErrorDb(
					"Table `achievement_reward` (Entry: %u) has title (A: %u H: %u) for only one team.",
					entry, reward.titleId[0], reward.titleId[1]);

		if (reward.titleId[0]) {
			CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(
					reward.titleId[0]);
			if (!titleEntry) {
				sLog->outErrorDb(
						"Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_A`, set to 0",
						entry, reward.titleId[0]);
				reward.titleId[0] = 0;
			}
		}

		if (reward.titleId[1]) {
			CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(
					reward.titleId[1]);
			if (!titleEntry) {
				sLog->outErrorDb(
						"Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_H`, set to 0",
						entry, reward.titleId[1]);
				reward.titleId[1] = 0;
			}
		}

		//check mail data before item for report including wrong item case
		if (reward.sender) {
			if (!ObjectMgr::GetCreatureTemplate(reward.sender)) {
				sLog->outErrorDb(
						"Table `achievement_reward` (Entry: %u) has invalid creature entry %u as sender, mail reward skipped.",
						entry, reward.sender);
				reward.sender = 0;
			}
		} else {
			if (reward.itemId)
				sLog->outErrorDb(
						"Table `achievement_reward` (Entry: %u) does not have sender data but has item reward, item will not be rewarded.",
						entry);

			if (!reward.subject.empty())
				sLog->outErrorDb(
						"Table `achievement_reward` (Entry: %u) does not have sender data but has mail subject.",
						entry);

			if (!reward.text.empty())
				sLog->outErrorDb(
						"Table `achievement_reward` (Entry: %u) does not have sender data but has mail text.",
						entry);
		}

		if (reward.itemId) {
			if (!ObjectMgr::GetItemPrototype(reward.itemId)) {
				sLog->outErrorDb(
						"Table `achievement_reward` (Entry: %u) has invalid item id %u, reward mail will not contain item.",
						entry, reward.itemId);
				reward.itemId = 0;
			}
		}

		m_achievementRewards[entry] = reward;
		++count;
	} while (result->NextRow());

	sLog->outString(">> Loaded %u achievement rewards in %u ms", count,
			GetMSTimeDiffToNow(oldMSTime));
	sLog->outString();
}

void AchievementGlobalMgr::LoadRewardLocales() {
	uint32 oldMSTime = getMSTime();

	m_achievementRewardLocales.clear(); // need for reload case

	QueryResult result =
			WorldDatabase.Query(
					"SELECT entry, subject_loc1, text_loc1, subject_loc2, text_loc2, subject_loc3, text_loc3, subject_loc4, text_loc4, "
							"subject_loc5, text_loc5, subject_loc6, text_loc6, subject_loc7, text_loc7, subject_loc8, text_loc8"
							" FROM locales_achievement_reward");

	if (!result) {
		sLog->outString(
				">> Loaded 0 achievement reward locale strings.  DB table `locales_achievement_reward` is empty");
		sLog->outString();
		return;
	}

	do {
		Field *fields = result->Fetch();

		uint32 entry = fields[0].GetUInt32();

		if (m_achievementRewards.find(entry) == m_achievementRewards.end()) {
			sLog->outErrorDb(
					"Table `locales_achievement_reward` (Entry: %u) has locale strings for non-existing achievement reward.",
					entry);
			continue;
		}

		AchievementRewardLocale& data = m_achievementRewardLocales[entry];

		for (int i = 1; i < TOTAL_LOCALES; ++i) {
			LocaleConstant locale = (LocaleConstant) i;
			std::string str = fields[1 + 2 * (i - 1)].GetString();
			sObjectMgr->AddLocaleString(str, locale, data.subject);

			str = fields[1 + 2 * (i - 1) + 1].GetString();
			sObjectMgr->AddLocaleString(str, locale, data.text);
		}
	} while (result->NextRow());

	sLog->outString(">> Loaded %lu achievement reward locale strings in %u ms",
			(unsigned long) m_achievementRewardLocales.size(),
			GetMSTimeDiffToNow(oldMSTime));
	sLog->outString();
}

void AchievementMgr::Compress(WorldPacket &packet, uint32 newOpcode) {
	uint32 pSize = packet.wpos();
	uint32 destsize = compressBound(pSize);
	packet.resize(destsize + sizeof(uint32));
	packet.put<uint32>(0, pSize);

	Compress(const_cast<uint8*>(packet.contents()) + sizeof(uint32), &destsize,
			(void*) packet.contents(), pSize);
	if (destsize == 0)
		return;

	packet.resize(destsize + sizeof(uint32));
	packet.SetOpcode(newOpcode);
}

void AchievementMgr::Compress(void* dst, uint32 *dst_size, void* src,
		int src_size) {
	z_stream c_stream;

	c_stream.zalloc = (alloc_func) 0;
	c_stream.zfree = (free_func) 0;
	c_stream.opaque = (voidpf) 0;

	// default Z_BEST_SPEED (1)
	int z_res = deflateInit(&c_stream, sWorld->getIntConfig(CONFIG_COMPRESSION));
	if (z_res != Z_OK) {
		sLog->outError(
				"Can't compress update packet (zlib: deflateInit) Error code: %i (%s)",
				z_res, zError(z_res));
		*dst_size = 0;
		return;
	}

	c_stream.next_out = (Bytef*) dst;
	c_stream.avail_out = *dst_size;
	c_stream.next_in = (Bytef*) src;
	c_stream.avail_in = (uInt) src_size;

	z_res = deflate(&c_stream, Z_NO_FLUSH);
	if (z_res != Z_OK) {
		sLog->outError(
				"Can't compress update packet (zlib: deflate) Error code: %i (%s)",
				z_res, zError(z_res));
		*dst_size = 0;
		return;
	}

	if (c_stream.avail_in != 0) {
		sLog->outError(
				"Can't compress update packet (zlib: deflate not greedy)");
		*dst_size = 0;
		return;
	}

	z_res = deflate(&c_stream, Z_FINISH);
	if (z_res != Z_STREAM_END) {
		sLog->outError(
				"Can't compress update packet (zlib: deflate should report Z_STREAM_END instead %i (%s)",
				z_res, zError(z_res));
		*dst_size = 0;
		return;
	}

	z_res = deflateEnd(&c_stream);
	if (z_res != Z_OK) {
		sLog->outError(
				"Can't compress update packet (zlib: deflateEnd) Error code: %i (%s)",
				z_res, zError(z_res));
		*dst_size = 0;
		return;
	}

	*dst_size = c_stream.total_out;
}
